package com.video.tiktokdownloader.nowatermark

import android.app.Application
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.content.FileProvider
import androidx.fragment.app.viewModels
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.Observer
import androidx.paging.Config
import androidx.paging.PagedListAdapter
import androidx.paging.toLiveData
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.video.tiktokdownloader.nowatermark.bean.MediaEntity
import kotlinx.android.synthetic.main.fragment_saved.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File

/**
 * @author Afra55
 * @date 2020/6/29
 * A smile is the best business card.
 * 没有成绩，连呼吸都是错的。
 */
class SavedFragment : BaseFragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_saved, container, false)
    }
    private val viewModel by viewModels<MyViewModel>()

    var menuPopupWindow:PopupWindow? = null

    val presenter by lazy {
        ApiPresenter(myActivity, object :Listener{
            override fun onView(type: Int, any: Any?) {

            }
        })
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val adapter = ViewAdapter(object : OnMediaItemClick{
            override fun click(mediaEntity: MediaEntity) {
                try {
                    val file = if (mediaEntity.what == 0) {
                            File(myActivity.getVideoDir(), mediaEntity.fileName)
                     }else if (mediaEntity.what == 1) {
                        File(myActivity.getMusicDir(), mediaEntity.fileName)
                    } else {
                        null
                    }
                    if (file != null){
                        if (file.exists()) {
                            val intent = Intent(myActivity, VideoShowActivity::class.java)
                            intent.putExtra("media", mediaEntity)
                            startActivity(intent)
                            myActivity.showInterstitial(1)
                        } else {
                            mediaEntity.originUrl?.let { presenter.doAction(it, mediaEntity.what) }
                        }

                    }
                } catch (e: Exception) {
                }
            }

            override fun more(view: View, mediaEntity: MediaEntity) {

                showPopupWindow(view, mediaEntity)
            }

        })
        viewModel.allMediaLiveData.observe(viewLifecycleOwner, Observer {
            if (it.isEmpty()) {
            } else {
            }
            adapter.submitList(it)
        })

        saved_rv.adapter = adapter

    }

    fun showPopupWindow(view: View, mediaEntity: MediaEntity) {
        if (menuPopupWindow == null) {
            menuPopupWindow = PopupWindow(View.inflate(myActivity, R.layout.pop_saved_menu, null), ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            // 设置背景
            // 设置背景
            menuPopupWindow!!.setBackgroundDrawable(ColorDrawable())
            // 外部点击事件
            // 外部点击事件
            menuPopupWindow!!.isOutsideTouchable = true

        }

        val contentView = menuPopupWindow?.contentView
        contentView?.findViewById<View>(R.id.pop_saved_menu_share)?.setOnClickListener {

            doShare(mediaEntity)
        }
        contentView?.findViewById<View>(R.id.pop_saved_menu_download)?.setOnClickListener {

            doShare(mediaEntity, true)
        }

        contentView?.findViewById<View>(R.id.pop_saved_menu_copy_link)?.setOnClickListener {

            val cm =
                myActivity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            cm.setPrimaryClip(ClipData.newPlainText("copy", mediaEntity.originUrl))
            myActivity.showToast("Link copied")
        }

        contentView?.findViewById<View>(R.id.pop_saved_menu_delete)?.setOnClickListener {
            menuPopupWindow?.dismiss()
            AppApplication.dao.delete(mediaEntity)
        }

        menuPopupWindow?.showAsDropDown(view)
    }

    fun doShare(mediaEntity: MediaEntity, justSave:Boolean = false) {
        GlobalScope.launch(Dispatchers.IO) {
            try {
                val what = mediaEntity.what
                if (what == 0) {
                    var fileName = mediaEntity.fileName!!
                    val file =  File(myActivity.getVideoDir(), fileName)
                    val destFile = File(myActivity.getVideoDir(true), fileName)
                    file.copyTo(destFile, true)
                    val fromFile = FileProvider.getUriForFile(
                        myActivity,
                        "${myActivity.packageName}.fileprovider",
                        destFile
                    )
                    myActivity.sendBroadcast(
                        Intent(
                            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                            fromFile
                        )
                    )

                    myActivity.sendBroadcast(
                        Intent(
                            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                            Uri.fromFile(destFile)
                        )
                    )
                    GlobalScope.launch(Dispatchers.Main) {
                        try {
                            myActivity.showToast("The video has been saved in: ${destFile.absolutePath}")

                            if (!justSave) {

                                try {
                                    val shareIntent = Intent()
                                    shareIntent.action = Intent.ACTION_SEND
                                    shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
                                    try {
                                        shareIntent.putExtra(
                                            Intent.EXTRA_STREAM,
                                            fromFile
                                        )
                                    } catch (e: Exception) {
                                        e.printStackTrace()
                                    }
                                    shareIntent.type = "video/*"

                                    startActivity(Intent.createChooser(shareIntent, "Share to"))

                                } catch (e: Exception) {
                                }
                            }
                        } catch (e: Exception) {
                        }
                    }
                }else if (what == 1) {
                    var fileName = mediaEntity.fileName!!
                    val file =  File(myActivity.getMusicDir(), fileName)
                    val destFile = File(myActivity.getMusicDir(true), fileName)
                    file.copyTo(destFile, true)
                    val fromFile = FileProvider.getUriForFile(
                        myActivity,
                        "${myActivity.packageName}.fileprovider",
                        destFile
                    )
                    myActivity.sendBroadcast(
                        Intent(
                            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                            fromFile
                        )
                    )

                    myActivity.sendBroadcast(
                        Intent(
                            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                            Uri.fromFile(destFile)
                        )
                    )
                    GlobalScope.launch(Dispatchers.Main) {
                        try {
                            myActivity.showToast("The music has been saved in: ${destFile.absolutePath}")

                            if (!justSave) {
                                try {
                                    val shareIntent = Intent()
                                    shareIntent.action = Intent.ACTION_SEND
                                    shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT)
                                    try {
                                        shareIntent.putExtra(
                                            Intent.EXTRA_STREAM,
                                            fromFile
                                        )
                                    } catch (e: Exception) {
                                        e.printStackTrace()
                                    }
                                    shareIntent.type = "audio/*"

                                    startActivity(Intent.createChooser(shareIntent, "Share to"))

                                } catch (e: Exception) {
                                }
                            }
                        } catch (e: Exception) {
                        }
                    }
                }
            } catch (e: Exception) {
            }
        }
    }
}

interface OnMediaItemClick {
    fun click(mediaEntity: MediaEntity)
    fun more(view: View, mediaEntity: MediaEntity)
}

class ViewAdapter(val onMediaItemClick: OnMediaItemClick) :
    PagedListAdapter<MediaEntity, ViewHolder>(
        diffCallback
    ) {
    companion object {
        /**
         * This diff callback informs the PagedListAdapter how to compute list differences when new
         * PagedLists arrive.
         * <p>
         * When you add a Cheese with the 'Add' button, the PagedListAdapter uses diffCallback to
         * detect there's only a single item difference from before, so it only needs to animate and
         * rebind a single view.
         *
         * @see DiffUtil
         */
        private val diffCallback = object : DiffUtil.ItemCallback<MediaEntity>() {
            override fun areItemsTheSame(oldItem: MediaEntity, newItem: MediaEntity): Boolean =
                oldItem.id == newItem.id

            /**
             * Note that in kotlin, == checking on data classes compares all contents, but in Java,
             * typically you'll implement Object#equals, and use it to compare object contents.
             */
            override fun areContentsTheSame(oldItem: MediaEntity, newItem: MediaEntity): Boolean =
                (oldItem.savedTime == newItem.savedTime) && (oldItem.downloadUrl == newItem.downloadUrl) && (oldItem.cover == newItem.cover)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            LayoutInflater.from(parent.context).inflate(
                R.layout.rv_item,
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        getItem(position)?.let { holder.find(it, onMediaItemClick) }
    }

}

class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    val cover = itemView.findViewById<ImageView>(R.id.rv_item_cover)
    val name = itemView.findViewById<TextView>(R.id.rv_item_name)
    val desc = itemView.findViewById<TextView>(R.id.rv_item_desc)
    val more = itemView.findViewById<ImageView>(R.id.rv_item_more)

    fun find(mediaEntity: MediaEntity, onMediaItemClick: OnMediaItemClick) {
        Glide.with(cover).load(mediaEntity.cover).centerCrop().into(cover)
        if (mediaEntity.what == 0) {
            name.text = mediaEntity.userName
        } else if (mediaEntity.what == 1) {
            name.text = mediaEntity.name
        }
        val desc1 = mediaEntity.desc
        if (desc1.isNullOrEmpty()) {
            desc.visibility = View.GONE
        } else {
            desc.visibility = View.VISIBLE
            desc.text = desc1
        }
        itemView.setOnClickListener { onMediaItemClick.click(mediaEntity) }
        more.setOnClickListener {
            onMediaItemClick.more(more, mediaEntity)
        }
    }
}

class MyViewModel(app: Application) : AndroidViewModel(app) {

    val dao = AppApplication.dao

    val allMediaLiveData = dao.pageAllMedia().toLiveData(
        Config(pageSize = 50, enablePlaceholders = true, maxSize = 300)
    )
}